package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 拦截所有路径，完成redis中token刷新
 *
 * @author 24040
 * @name ReflashTokenInterceptor
 * @date 2022-09-04 17:30
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从请求头中获取token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        // 2.基于token，从redis获取用户
        String tokenKey = RedisConstants.LOGIN_USER_KEY.concat(token);
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(tokenKey);
        // 判空用户是否存在，token是否过期
        if(entries.isEmpty()){
            return true;
        }
        // 3.将查询到的Hash转换为UserDto
        UserDTO user = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);

        // 保存到threadLocal中
        UserHolder.saveUser(user);

        // 4.进行redis有效期的刷新
        redisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 放行
        return true;
    }


    /**
     * 在响应完成之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
